import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths } from '@/utils/typings.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Progress, Space, Table, Tooltip } from 'antd';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import CreateIotSim from './components/CreateIotSim';
import ExportModal from './components/ExportModal';
import MultiCreateSim from './components/MultiCreateSim';
import SimInfoModal from './components/SimInfoModal';
import UpdateIotSim from './components/UpdaetIotSim';
import {
  deleteMultiIotSim,
  discardMultiIotSim,
  queryIotSimList,
  removeIotSim,
  updateMultiIotSim,
} from './service';
import type { IotSimTableListItem, MultiSimOperInfo } from './typings.d';
import { getFlowPercent } from './utils';

const IotSimList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.iotSim || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const [currIotSim, setCurrIotSim] = useState<IotSimTableListItem | null>(null);
  const [updateVisible, setUpdateVisible] = useState<boolean>(false);
  const [infoVisible, setInfoVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<IotSimTableListItem>[] = [
    {
      title: 'key',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '流量卡号',
      width: 300,
      hideInForm: true,
      dataIndex: 'iccid',
      align: 'center',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setCurrIotSim(record);
              setInfoVisible(true);
            }}
          >
            {record.iccid}
          </a>
        </>
      ),
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      align: 'center',
      hideInSearch: true,
      valueType: 'date',
    },
    {
      title: '设备类型',
      width: 120,
      dataIndex: 'deviceType',
      align: 'center',
      valueEnum: {
        0: { text: '视频巡检车' },
        1: { text: 'GPS设备' },
        2: { text: '4G车位锁' },
        3: { text: '4G流量主机' },
        4: { text: '诱导屏控制卡' },
        99: { text: '其他设备' },
      },
    },
    {
      title: '供应商',
      dataIndex: 'provider',
      align: 'center',
      valueEnum: {
        tibiot: { text: '齐犇' },
        upiot: { text: '量讯' },
        dahan: { text: '大汉三通' },
      },
    },
    {
      title: '运营商',
      dataIndex: 'supplier',
      align: 'center',
      valueEnum: {
        CMCC: { text: '中国移动' },
        CTCC: { text: '中国电信' },
        CUCC: { text: '中国联通' },
      },
    },
    {
      title: '套餐名称',
      dataIndex: 'pkgName',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '流量大小',
      hideInSearch: true,
      dataIndex: 'totalFlow',
      align: 'center',
    },
    {
      title: '已用流量',
      hideInSearch: true,
      dataIndex: 'usedFlow',
      align: 'center',
    },
    {
      title: '剩余流量',
      hideInSearch: true,
      hideInForm: true,
      dataIndex: 'usedFlow',
      align: 'center',
      render: (_, record) => {
        const per = getFlowPercent(record.usedFlow, record.totalFlow);
        const preRemain = 100 - Number(per) >= 0 ? 100 - Number(per) : 0;
        const remain = Number(preRemain.toFixed(2));
        if (remain > 10) {
          return (
            <Tooltip title={`${remain}%`}>
              <Progress
                style={{ minWidth: '110px', maxWidth: '200px' }}
                success={{ percent: remain }}
                showInfo={false}
                percent={remain}
                size="small"
              />
            </Tooltip>
          );
        } else {
          return (
            <Tooltip title={`${remain}%`}>
              <Progress
                status="exception"
                style={{ minWidth: '110px', maxWidth: '200px' }}
                showInfo={false}
                percent={remain}
                size="small"
              />
            </Tooltip>
          );
        }
      },
    },

    {
      title: '激活时间',
      dataIndex: 'activeTime',
      align: 'center',
      hideInSearch: true,
      valueType: 'date',
    },
    {
      title: '过期时间',
      dataIndex: 'pkgExpiredTime',
      align: 'center',
      // hideInSearch: true,
      valueType: 'date',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'application',
      align: 'center',
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      key: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record, x, action) =>
        ifDelete || ifModify
          ? [
              ifModify && (
                <a
                  key={`${record._id}_modify`}
                  onClick={() => {
                    setCurrIotSim(record);
                    setUpdateVisible(true);
                  }}
                >
                  编辑
                </a>
              ),
              ifDelete && (
                <ConfirmModal
                  key={`${record._id}_delete`}
                  reload={() => action?.reload()}
                  operFunc={async () => await removeIotSim(record._id)}
                />
              ),
            ]
          : [<PlaceHolderCpn key={record._id} />],
    },
  ];
  return (
    <PageHeaderWrapper
      title={false}
      content="此处展示所有供应商的流量卡，临近30天过期时会通知到钉钉群，过期三天后将自动舍弃"
    >
      <ProTable
        rowKey="iccid"
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        search={{ labelWidth: 'auto' }}
        columns={columns}
        actionRef={actionRef}
        request={async (params, sort) => {
          const res = await queryIotSimList(params, sort);
          return res;
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL],
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        )}
        tableAlertOptionRender={({ selectedRows, onCleanSelected }) => {
          const operInfo: MultiSimOperInfo[] =
            selectedRows?.map((item) => {
              return {
                id: item._id,
                iccid: item.iccid,
                ownerId: item.ownerId,
                provider: item.provider,
              };
            }) || [];
          return ifModify || ifDelete ? (
            <Space size={16}>
              {ifModify && (
                <ConfirmModal
                  key={'muliti_modify'}
                  titleText="批量更新"
                  btnText="批量更新"
                  reload={() => {
                    onCleanSelected();
                    actionRef.current?.reload();
                  }}
                  text={'确定要更新这些流量卡吗？'}
                  operFunc={async () => await updateMultiIotSim({ sims: operInfo })}
                />
              )}
              {ifDelete && (
                <ConfirmModal
                  key={'muliti_delete'}
                  btnText="批量删除"
                  reload={() => {
                    onCleanSelected();
                    actionRef.current?.reload();
                  }}
                  text={'确定要删除这些流量卡吗？'}
                  operFunc={async () => await deleteMultiIotSim({ sims: operInfo })}
                />
              )}
              {ifDelete && (
                <ConfirmModal
                  key={'muliti_discard'}
                  btnText="批量舍弃"
                  reload={() => {
                    onCleanSelected();
                    actionRef.current?.reload();
                  }}
                  text={'确定要舍弃这些流量卡吗？'}
                  operFunc={async () => await discardMultiIotSim({ sims: operInfo })}
                />
              )}
            </Space>
          ) : (
            <PlaceHolderCpn />
          );
        }}
        dateFormatter="string"
        pagination={{
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        toolBarRender={(action) => [
          <ExportModal key="iotsim_export" />,
          ifCreate && <MultiCreateSim key="iotsim_multicreate" reload={() => action?.reload()} />,
          ifCreate && <CreateIotSim key="iotsim_create" reload={() => action?.reload()} />,
        ]}
      />
      {updateVisible && currIotSim && (
        <UpdateIotSim
          visible={updateVisible}
          iotSim={currIotSim}
          setUnvisible={() => {
            setCurrIotSim(null);
            setUpdateVisible(false);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
        />
      )}
      {infoVisible && currIotSim && (
        <SimInfoModal
          visible={infoVisible}
          hideModalVisible={() => {
            setCurrIotSim(null);
            setInfoVisible(false);
          }}
          simItem={currIotSim}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default IotSimList;
